package com.demo.excel;

import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.demo.eneity.User;
import com.demo.mapper.UserMapper;
import com.demo.utils.AMapUtils;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.*;

@Getter
@Component
@Slf4j
public class SimpleThreadListener extends AnalysisEventListener<User> {

    private List<User> list = Collections.synchronizedList(new ArrayList<>());

    public SimpleThreadListener() {

    }

    @Override
    public void invoke(User user, AnalysisContext analysisContext) {
        if (user != null) {
            list.add(user);
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

        log.info("解析完毕，开始插入");
        // 根据 hotelName 去重
//        List<User> uniqueList = removeDuplicatesByHotelName(list);
//        for (User user : list) {
//            double[] doubles = AMapUtils.addressToGPS(user.getHotelAddress());
//            if (doubles!= null) {
//                user.setLatitude(String.valueOf(doubles[0]));
//                user.setLongitude(String.valueOf(doubles[1]));
//            } else {
//                // Handle the case where coordinates cannot be obtained
//                user.setLatitude(null);
//                user.setLongitude(null);
//            }
//        }
        for (int i = 0; i < list.size(); i++) {
            User user = list.get(i);
            if(user.getEventName()==null){
                user.setEventName(list.get(i-1).getEventName());
            }
            if(user.getHotelName()==null){
                user.setHotelName(list.get(i-1).getHotelName());
            }
            if(user.getHotelAddress()==null){
                user.setHotelAddress(list.get(i-1).getHotelAddress());
            }
        }
        UserMapper userMapper = SpringUtil.getBean(UserMapper.class);
        userMapper.insertBatchSomeColumn(list);
    }

    /**
     * 根据 hotelName 对 User 列表进行去重
     * @param users 包含 User 对象的列表
     * @return 去重后的 User 列表
     */
    private List<User> removeDuplicatesByHotelName(List<User> users) {
        Map<String, User> uniqueMap = new LinkedHashMap<>();
        for (User user : users) {
            if (user.getHotelName() != null) {
                uniqueMap.putIfAbsent(user.getHotelName(), user);
            }
        }
        return new ArrayList<>(uniqueMap.values());
    }
}
